<template>
  <div class="register-form">
    <el-form label-width="80px" label-position="left" :model="form" :rules="rules" status-icon ref="form" :hide-required-asterisk="true">
      <el-form-item label="登录名" prop="name">
        <el-input placeholder="会员名一旦设置成功将无法修改" v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input placeholder="设置你的登录密码" v-model="form.pass" type="password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码确认" prop="checkPass">
        <el-input placeholder="请再次输入你的密码" v-model="form.checkPass" type="password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="submitForm('form')">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import { register } from '@/api/account.js'
  import { setToken } from '@/utils/auth'
  export default{
    data() {
      var validateName = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入登录名'));
        } else {
          callback();
        }
      };
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.form.checkPass !== '') {
            this.$refs.form.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.form.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        form: {
          name:'',
          pass:'',
          checkPass:''
        },
        rules:{
          name:[{required: true,validator:validateName,trigger:'blur'}],
          pass:[{required: true,validator:validatePass,trigger:'blur'}],
          checkPass:[{required: true,validator:validatePass2,trigger:'blur'}],
        }
      };
    },
    methods: {
      submitForm(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            this.handleRegister()
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      async handleRegister(){
        let res = await register(this.form.name,this.form.pass)
        if(res.code == 200){
          this.$message({
            type:'success',
            message:'注册成功'
          })
        }
        else{
          this.$message.error(res.message)
        }
      }
    },
  }
</script>

<style scoped>
  .register-form{
    width: 400px;
    margin: 40px auto;
  }
</style>
